package com.normal.zbase.impl.tools.obj

import android.annotation.SuppressLint
import com.normal.zbase.impl.http.ApiLoginFactory
import com.normal.zbase.impl.tools.extend.logger
import com.normal.zbase.impl.tools.utils.file.FileUtil
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File

object DowloadManager {

    /**
     * 图片下载
     * @param remoteImgPath 远程图片地址
     * @param file 下载的本地图片地址
     *
     */
    @SuppressLint("CheckResult")
    fun downloadImg(
        remoteImgPath: String,
        file: File?,
        onSucc: (() -> Unit) = {},
        onFail: ((Throwable) -> Unit) = {}
    ) {
        ApiLoginFactory.downloadFile(remoteImgPath)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .map { responseBody ->
                //1、创建文件
                val bytes = responseBody.bytes()
                if (file == null) {
                    Observable.error<NullPointerException>(
                        java.lang.NullPointerException(
                            "文件为null"
                        )
                    )
                }
                //2、文件存储
                FileUtil.writeFile(file!!, bytes)
                file!!
            }.flatMap { origin ->
                //默认不能超过200kb
                val MAX_SIZE = 200 * 1024
                //图片不能过小，低于10KB
                val MIN_SIZE = 10 * 1024
                FileUtil.requestPicCompressObservable(origin, 720)
                    .flatMap { fistFile ->
                        if (fistFile.exists()) {
                            val len = fistFile.length()
                            when {
                                len >= MAX_SIZE -> {
                                    // 补偿进行二次压缩
                                    logger.info("补偿进行二次压缩:\n $fistFile <$len>")
                                    var secondFile =
                                        FileUtil.requestPicCompressObservable(origin, 360)
                                    fistFile.delete()
                                    secondFile
                                }
                                len <= MIN_SIZE -> Observable.just(origin)
                                else -> Observable.just(fistFile)
                            }
                        } else {
                            Observable.error(NullPointerException("压缩文件错误：\n$fistFile> is NULL "))
                        }
                    }
            }.subscribe({
                logger.info("文件下载成功:\n${it.absolutePath}")
                onSucc.invoke()
            }, {

                logger.info("文件下载失败:\n${it.printStackTrace()}")
                onFail.invoke(it)
            }, {
                logger.info("删除原图:")
                FileUtil.fileDelete(file)
            })
    }
}